package app

import (
	"encoding/json"
	"errors"
	"gitee.com/zmhfly8/gm/global"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v4"
	"time"
)

type Claims struct {
	Channel  string   `json:"channel"`
	UserInfo UserInfo `json:"userInfo"`
	jwt.RegisteredClaims
}
type UserInfo struct {
	ID       int64    `json:"id"`
	UCode    string   `json:"uCode"`
	NickName string   `json:"nickName"`
	TrueName string   `json:"TrueName"`
	Mobile   string   `json:"mobile"`
	OpenId   string   `json:"openId"`
	RoleCode []string `json:"roleCode"`
}

func GetJWTSecret() []byte {

	return []byte(global.JWT.Secret)
}
func GenerateToken(expire time.Duration, userInfo UserInfo, issuer string, channel string) (string, time.Time, error) {

	expireTime := jwt.NewNumericDate(time.Now().Add(expire))
	claims := Claims{
		UserInfo: userInfo,
		Channel:  channel,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: expireTime,
			Issuer:    issuer,
		},
	}

	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	token, err := tokenClaims.SignedString(GetJWTSecret())
	return token, expireTime.Time, err
}

func ParseToken(token string) (*Claims, error) {
	tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return GetJWTSecret(), nil
	})
	if err != nil {
		return nil, err
	}
	if tokenClaims != nil {
		if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
			return claims, nil
		}
	}

	return nil, err
}
func GetMemberInfo(c *gin.Context) (Claims, error) {
	var td Claims
	j, b := c.Get("loginUser")
	if b {
		str := []byte(j.(string))
		json.Unmarshal(str, &td)
	}
	if td.Channel != "api" {
		return Claims{}, errors.New("非法登录")
	}
	return td, nil
}
func GetAdminInfo(c *gin.Context) (Claims, error) {
	var td Claims
	j, b := c.Get("loginUser")
	if b {
		str := []byte(j.(string))
		json.Unmarshal(str, &td)
	}
	if td.Channel != "admin" {
		return Claims{}, errors.New("非法登录")
	}
	return td, nil
}
